package com.ruoyi.work.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.work.domain.WorkCost;
import com.ruoyi.work.mapper.WorkCostMapper;
import com.ruoyi.work.service.IWorkCostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.List;

/**
 * @Author: MMDZ
 * @Desc:
 */
@Service
public class WorkCostServiceImpl implements IWorkCostService {
    private static final Logger log = LoggerFactory.getLogger(WorkCostServiceImpl.class);

    @Autowired
    private WorkCostMapper workCostMapper;
    @Autowired
    protected Validator validator;

    @Override
    public List<WorkCost> selectWorkCostList(WorkCost workCost) {
        return workCostMapper.selectWorkCostList(workCost);
    }

    @Override
    public WorkCost selectWorkCostById(Long costId) {
        return workCostMapper.selectWorkCostById(costId);
    }

    @Override
    public String checkUserUnique(WorkCost workCost) {
        Long costId = StringUtils.isNull(workCost.getCostId()) ? -1L : workCost.getCostId();
        WorkCost info = workCostMapper.checkUserUnique(workCost.getUserId());
        if (StringUtils.isNotNull(info) && info.getCostId().longValue() != costId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertWorkCost(WorkCost workCost) {
        return workCostMapper.insertWorkCost(workCost);
    }

    @Override
    public int updateWorkCost(WorkCost workCost) {
        return workCostMapper.updateWorkCost(workCost);
    }

    @Override
    public int deleteWorkCostByIds(Long[] costIds) {
        return workCostMapper.deleteWorkCostByIds(costIds);
    }

    /**
     * 导入成本数据
     *
     * @param costList        数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importData(List<WorkCost> costList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(costList) || costList.size() == 0) {
            throw new ServiceException("导入人力成本数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 查询所有用户
        List<SysUser> allUserList = workCostMapper.selectAllUser();
        // 查询所有人力成本
        List<WorkCost> allCostList = workCostMapper.selectWorkCostList(null);

        for (WorkCost cost : costList) {
            try {
                SysUser u = allUserList.stream().filter(a -> a.getUserName().equals(cost.getUserName().trim())).findFirst().orElse(null);
                // 验证用户是否存在系统内
                if (StringUtils.isNotNull(u)) {
                    WorkCost oldCost = allCostList.stream().filter(a -> a.getUserName().equals(cost.getUserName())).findFirst().orElse(null);
                    if (StringUtils.isNotNull(oldCost)) {
                        // 更新
                        oldCost.setWeekPay(cost.getWeekPay());
                        oldCost.setDayPay(cost.getDayPay());
                        oldCost.setHourPay(cost.getHourPay());
                        oldCost.setUpdateBy(operName);
                        BeanValidators.validateWithException(validator, oldCost);
                        this.updateWorkCost(oldCost);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、账号 " + cost.getUserName() + " 更新成功");
                    } else {
                        // 新增
                        cost.setUserId(u.getUserId());
                        cost.setCreateBy(operName);
                        BeanValidators.validateWithException(validator, cost);
                        this.insertWorkCost(cost);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、账号 " + cost.getUserName() + " 导入成功");
                    }
                } else {
                    // 用户不在系统内
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + cost.getUserName() + " 导入失败，该用户未录入系统内！！！");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + cost.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
